<?php

namespace IDock\Insurance\JTIC\Response;


use IDock\Http\Response;

class AllJTICResponse extends Response
{

    public function resolve(): Response
    {
        $body = $this->getBody();

        if ($body) {
            libxml_disable_entity_loader(false);
            $body = str_replace(['<![CDATA[',']]>'],['',''],$body);
            $body = simplexml_load_string($body);

            $body = $this->objectToArray($body);

            if ($this->printer) {
                $this->printer = new $this->printer;
            }

            $returnCode = $body['returnCode'] ?? '';

            if ($returnCode === '0') {
                $bizContent = $body['bizContent']['Packet'] ?? '';
                if($bizContent) {
                    $errorCode = $bizContent['InterfaceMsg']['ErrorCode'] ?? '';
                    $errorMessage = $bizContent['InterfaceMsg']['ErrorMessage'] ?? '';
                    if ($errorCode == '1000') {
                        return $this;
                    }

                    if ($errorCode != '0000') {
                        $this->setError($errorMessage);
                        $this->setCode(500);
                        return $this;
                    }
                }

                $this->setBody($bizContent);
            } else {
                $returnMsg = $body['returnMsg'] ?? '';
                $this->setCode($returnCode);
                $this->setError($returnMsg);
            }
        }

        return $this;
    }

    public function formatArray($arr): array
    {
        if (empty($arr)) return [];
        if (!is_array($arr)) {
            return [];
        }
        if (!isset($arr[0])) {
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }

    protected function objectToArray($object) {
        if( count($object)==0 )  return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }
}
